package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BookOrderInfo;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.PayAndBackParams;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.entity.SysDistrict;
import com.isunland.managesystem.entity.SysDistrictListOriginal;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能: 添加预约订单
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/1/5 21:08
 */

public class AppointmentOrderUpdateFragment extends Fragment {
  public static final String EXTRA_DETAIL = "com.isunland.intelligentFarmbyWJ.EXTRA_ITEM";
  public static final int REQUEST_OPERATION_TIME = 1;
  private static final int TYPE_SAVE = 2;
  /**
   * 提交操作
   */
  private static final int TYPE_SUBMIT = 3;
  private static final int REQUEST_PAY = 4;
  private static final int REQUEST_MAP_LOCATION = 5;
  private static final int REQUEST_SELECT_ADDRESS = 6;
  //public static final int REQUEST_TYPE = 2;
  //public static final int REQUEST_OBJECT = 3;

  @BindView(R.id.tv_operationTime) TextView tvOperationTime;
  @BindView(R.id.tv_appointTaskDesc) EditText tvAppointTaskDesc;
  @BindView(R.id.tv_operationLocation) TextView tvOperationLocation;
  @BindView(R.id.tv_cooperativeRegion) TextView tvCooperativeRegion;
  @BindView(R.id.tv_landArea) EditText tvLandArea;
  @BindView(R.id.tv_contacts) EditText tvContacts;
  @BindView(R.id.tv_contactPhone) EditText tvContactPhone;
  //@BindView(R.id.tv_appointAccount)
  //EditText tvAppointAccount;
  //@BindView(R.id.tv_bookAccount)
  //EditText tvBookAccount;
  @BindView(R.id.tv_regionX) TextView tvRegionX;//经度
  @BindView(R.id.tv_regionY) TextView tvRegionY;//维度
  @BindView(R.id.tv_bookAccount) EditText tvBookAccount;
  //@BindView(R.id.tv_appointAccount)
  //EditText tvAppointAccount;
  @BindView(R.id.tv_bookDeposit) EditText tvBookDeposit;

  private BaseVolleyActivity mActivity;

  private FragmentManager mFm;
  private BookOrderInfo mItem;
  private String mId;
  /** 单据编号 */
  private String mBookNo;
  private CurrentUser mCurrentUser;
  /**
   * 选择地址的编码.
   */
  private String mCooperativeRegionCode;//可接单区域Code..
  //private String mCooperativeRegion;//可接单区域

  public static Fragment newInstance(BookOrderInfo item) {
    AppointmentOrderUpdateFragment fragment = new AppointmentOrderUpdateFragment();
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_DETAIL, item);
    fragment.setArguments(args);
    return fragment;
  }

  public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mItem = (BookOrderInfo) getArguments().getSerializable(EXTRA_DETAIL);
    mActivity = (BaseVolleyActivity) getActivity();
    mFm = mActivity.getSupportFragmentManager();
    mCurrentUser = CurrentUser.newInstance(mActivity);
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
      if (mItem == null) {
        mId = UUID.randomUUID().toString();
        mBookNo = MyDateUtil.getOrderNo();
        actionBar.setTitle(
            MyStringUtil.connect(getString(R.string.add1), getString(R.string.appointmentOrder1)));
      } else {
        actionBar.setTitle(
            MyStringUtil.connect(getString(R.string.alter), getString(R.string.appointmentOrder1)));
        mId = mItem.getId();
        mBookNo = mItem.getBookNo();
      }
    }
    super.onCreate(savedInstanceState);
  }

  //private void initView(View v) {
  //    tvOperationLocation.setEnabled(true);
  //    tvOperationLocation.setHint(R.string.hintInput);
  //    tvLandArea.setEnabled(true);
  //    tvLandArea.setHint(R.string.hintInput);
  //    tvOperationTime.setHint(R.string.hintSelect);
  //    //tvType.setHint(R.string.hintSelect);
  //    //tvObject.setHint(R.string.hintSelect);
  //    tvContacts.setEnabled(true);
  //    tvContacts.setHint(R.string.hintInput);
  //    tvContactPhone.setEnabled(true);
  //    tvContactPhone.setHint(R.string.hintInput);
  //
  //
  //
  //}

  //初始化界面
  @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_appointment_order_update, container, false);
    ButterKnife.bind(this, v);
    initData(mItem);
    return v;
  }

  private void initData(BookOrderInfo data) {
    //像京东收货人一样,可以选别人
    //tvBookAccount.setEnabled(false);

    //新增
    if (data == null) {
      //默认当前登录人账号为预约人账号
      tvBookAccount.setText(mCurrentUser.getName());
      return;
    }

    //修改
    tvAppointTaskDesc.setText(data.getBookWordDesc());
    //noinspection deprecation
    tvOperationTime.setText(
        MyDateUtil.parseDateToString(MyDateUtil.stringToDate(data.getBookWorkDate())));

    tvContacts.setText(data.getLinkmanName());
    tvContactPhone.setText(data.getLinkmanPhone());
    //tvOperationLocation.setText(data.getWorkAreaAddress());//字段去掉了.
    tvLandArea.setText(String.valueOf(data.getWorkArea()));
    tvBookAccount.setText(data.getBookAccountNo());
    tvCooperativeRegion.setText(data.getCooperativeRegion());
    mCooperativeRegionCode = data.getCooperativeRegionCode();

    String address = data.getWorkAddress();
    String regionX = data.getRegionX();
    String regionY = data.getRegionY();
    setLocation(address, regionX, regionY);
  }

  /**
   * 根据所选地址设置控件,由于使用地方较多.抽取出单独的方法.
   *
   * @param address 地址
   * @param regionX 经度
   * @param regionY 维度.
   */
  private void setLocation(String address, String regionX, String regionY) {

    tvOperationLocation.setText(address);
    tvRegionX.setText(regionX);
    tvRegionY.setText(regionY);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_order_save_submit, menu);
    menu.getItem(1).setTitle(R.string.submitOrder);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    //if (item == null) return super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_save:
        volleyPostSave(TYPE_SAVE);
        return true;
      case R.id.menu_item_submit:
        volleyPostSave(TYPE_SUBMIT);

        return true;
    }

    return super.onOptionsItemSelected(item);
  }

  private void volleyPostSave(final int type) {
    if (TextUtils.isEmpty(mId)) return;

    //ToastUtil.show("添加");
    //String str0=  tvType.getText().toString().trim();
    //String account = tvAppointAccount.getText().toString().trim();
    String accountNo = tvBookAccount.getText().toString().trim();
    String time = tvOperationTime.getText().toString().trim();
    String desc = tvAppointTaskDesc.getText().toString().trim();
    String address = tvOperationLocation.getText().toString().trim();
    String area = tvLandArea.getText().toString().trim();
    String contract = tvContacts.getText().toString().trim();
    String contractPhone = tvContactPhone.getText().toString().trim();
    String cooperativeRegion = tvCooperativeRegion.getText().toString().trim();
    String regionX = tvRegionX.getText().toString().trim();
    String regionY = tvRegionY.getText().toString().trim();
    final String bookDeposit = tvBookDeposit.getText().toString().trim();

    boolean isComplete =

        //!TextUtils.isEmpty(account)
        !TextUtils.isEmpty(accountNo)
            && !TextUtils.isEmpty(time)
            && !TextUtils.isEmpty(desc)
            && !TextUtils.isEmpty(address)
            //&& !TextUtils.isEmpty(regionX)
            //&& !TextUtils.isEmpty(regionY)//感觉不用验证坐标
            && !TextUtils.isEmpty(area)
            && !TextUtils.isEmpty(cooperativeRegion)
            && !TextUtils.isEmpty(contract)
            && !TextUtils.isEmpty(contractPhone);

    if (!isComplete) {
      ToastUtil.show("请填写完整!");
      return;
    }

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ADD_APPOINT_ORDER);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("bookNo", mBookNo);
    params.put("jobNo", CurrentUser.newInstance(getActivity()).getJobNumber());
    params.put("bookAccountNo", accountNo);
    //params.put("bookAccountNo", accountNo);
    params.put("dataStatus", "new");
    //noinspection deprecation
    params.put("bookWorkDate", MyDateUtil.parseTimeToString(MyDateUtil.parseStringToDate(time)));
    params.put("bookWordDesc", desc);
    params.put("workAddress", address);//作业区域选择
    params.put("regionX", regionX);//作业区域选择
    params.put("regionY", regionY);//作业区域选择
    params.put("workArea", area);
    params.put("cooperativeRegion", cooperativeRegion);
    params.put("cooperativeRegionCode", mCooperativeRegionCode);
    params.put("linkmanName", contract);
    params.put("linkmanPhone", contractPhone);
    params.put("bookDeposit", bookDeposit);

    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("保存失败!");
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        //json = MyUtils.readAssetsFile(MyApplication.getAppContext(), "testOperationDetail.json");
        Base original = new Gson().fromJson(json, Base.class);
        if (original != null && original.getResult() == Base.SUCCESS) {
          ToastUtil.show("保存成功");
          mActivity.setResult(Activity.RESULT_OK);
          if (type == TYPE_SAVE) {
            mActivity.finish();
          }
          //如果预约保证金不为0,区支付.否则直接提交
          double bookDepositDouble = MyStringUtil.valueOfDouble(bookDeposit, 0);
          if (type == TYPE_SUBMIT) {
            if (bookDepositDouble != 0) {
              PayAndBackParams params = new PayAndBackParams();
              params.setId(UUID.randomUUID().toString());
              params.setEditable(false);
              params.setMainId(mId);
              params.setPayMuch(String.valueOf(bookDepositDouble));
              params.setMoneyType(PayAndBackParams.MONEY_TYPE_GARRENTEE_FEE);
              params.setBookOrderNo(mBookNo);
              params.setOrderType(PayAndBackParams.ORDER_TYPE_ORDER);
              PayAndBackActivity.newInstance(AppointmentOrderUpdateFragment.this,
                  PayAndBackActivity.class, params, REQUEST_PAY);
            } else {
              volleyPostSubmit();
            }
          }
        } else {
          ToastUtil.show("保存失败!");
        }
      }
    });
    //mActivity.setResult(Activity.RESULT_OK);
    //mActivity.finish();

  }

  private void volleyPostSubmit() {
    if (TextUtils.isEmpty(mId)) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_APPOINT_ORDER_STATUS);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", mId);
    params.put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode());
    params.put("dataStatus", "submit");
    MyUtils.showDialogLoading(mActivity, R.string.submit);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("提交失败");
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Base original = new Gson().fromJson(arg0, Base.class);
        if (original != null && original.getResult() == Base.SUCCESS) {
          ToastUtil.show("提交订单成功");
          mActivity.setResult(Activity.RESULT_OK);
          mActivity.finish();
        } else {
          ToastUtil.show("提交订单失败");
        }
      }
    });
  }

  @OnClick({ R.id.tv_operationTime, R.id.tv_operationLocation, R.id.tv_cooperativeRegion })
  public void onClick(View view) {
    if (view == null) return;
    switch (view.getId()) {
      case R.id.tv_operationTime:
        String time = tvOperationTime.getText().toString().trim();
        //noinspection deprecation
        showDialog(MyDateUtil.stringToDate(time), REQUEST_OPERATION_TIME);
        break;
      case R.id.tv_operationLocation://作业区域地址
        //ToastUtil.show("作业区域地址");
        String address = tvOperationLocation.getText().toString().trim();
        String regionX = tvRegionX.getText().toString().trim();
        String regionY = tvRegionY.getText().toString().trim();
        SelectLocationMapActivity.newInstance(this, mActivity, REQUEST_MAP_LOCATION, address,
            regionX, regionY);
        break;
      case R.id.tv_cooperativeRegion://可接单区域
        //ToastUtil.show("可接单区域");
        selectRegion();
        break;

      //case R.id.tv_type:
      //    volleyPostByType(REQUEST_TYPE);
      //    break;
      //case R.id.tv_object:
      //    volleyPostByType(REQUEST_OBJECT);
      //    break;
      default:
        break;
    }
  }

  /**
   * 选择区域
   */
  private void selectRegion() {
    //DialogFragment dialog = AddressSelectDialogFragment.newInstance("100");
    //dialog.setTargetFragment(AppointmentOrderUpdateFragment.this, REQUEST_SELECT_ADDRESS);
    //dialog.show(mFm, "");

    SimpleTreeListParams params = new SimpleTreeListParams();
    //noinspection unchecked
    params.setItem(new SysDistrict("中国", "100"));
    params.setChildField("code");
    params.setParentField("pcode");
    params.setTitleField("districtName");
    params.setTitle("选择地址");
    params.setClassOriginal(SysDistrictListOriginal.class);
    params.setUrl(ApiConst.URL_QUERY_LIST_ADDRESS);
    params.setParamsNotEmpty(new ParamsNotEmpty().put("pcode", "100").put("memberCode", ""));
    BaseVolleyActivity.newInstance(this, AddressTreeListActivity.class, params,
        REQUEST_SELECT_ADDRESS);
  }

/*
    */

  /**
   * 根据type类别,初始化选择信息.
   *
   * @param typeCode REQUEST类别.
   *//*

    private void volleyPostByType(final int typeCode) {
        String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DATA_DICT_TYPE);
        HashMap<String, String> params = new HashMap<>();
        switch (typeCode) {

            case REQUEST_TYPE:
                params.put("type", "workType");
                break;
            case REQUEST_OBJECT:
                //params.put("type","workObject");
                params.put("type", "workType");
                break;
            default:
                //ToastUtil.show("");
                return;
        }

        MyUtils.showDialogLoading(getActivity());
        mActivity.volleyPost(url, params, new VolleyResponse() {
            @Override
            public void onVolleyError(VolleyError arg0) {
                ToastUtil.show("获取失败");
            }

            @Override
            public void onVolleyResponse(String json) throws JSONException {
                //测试json数据.放在文件中.
                //基本信息验证.服务端返回默认是SelectOriginal格式的,解析成这个格式只是为了验证.
                //具体的使用还是要看具体的格式.


                SelectOriginal result = new Gson().fromJson(json, SelectOriginal.class);
                if (result == null || result.getResult() != Base.SUCCESS || result.getRows() == null || result.getRows().size() == 0) {
                    ToastUtil.show("获取失败");
                    return;
                }


                showDialog(result.getRows(), typeCode);
            }
        });


    }
*/
  protected void showDialog(Date date, int typeCode) {
    DialogFragment dialog = BaseYMDTimeDialogFragment.newInstance(date);
    dialog.setTargetFragment(AppointmentOrderUpdateFragment.this, typeCode);
    dialog.show(mFm, "");
  }

  //protected void showDialog(final ArrayList<BaseSelectObject> rows, int typeCode) {
  //    BaseArrayDialogFragment dialog = SimpleArrayDialogFragment.newInstance(rows);
  //    if (dialog == null) return;
  //    dialog.setTargetFragment(this, typeCode);
  //    dialog.show(mFm, "");
  //
  //}

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK) return;
    //if (requestCode == REQUEST_OBJECT && data != null) {
    //    mObject = (BaseSelectObject) data.getSerializableExtra(BaseArrayDialogFragment.EXTRA_VALUE);
    //    tvObject.setText(mObject.getName());
    //    return;
    //}

    if (requestCode == REQUEST_OPERATION_TIME && data != null) {
      Date date = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      tvOperationTime.setText(DateFormat.format(MyDateUtil.TYPE_DATE, date));
    }
    if (requestCode == REQUEST_PAY) {
      volleyPostSubmit();
    }
    if (requestCode == REQUEST_MAP_LOCATION) {
      String regionX = data.getStringExtra(SelectLocationMapFragment.EXTRA_LAT);
      String regionY = data.getStringExtra(SelectLocationMapFragment.EXTRA_LON);
      String address = data.getStringExtra(SelectLocationMapFragment.EXTRA_ADDRESS);
      setLocation(address, regionX, regionY);
    }
    if (requestCode == REQUEST_SELECT_ADDRESS) {
      //mCooperativeRegionCode = data.getStringExtra(AddressSelectDialogFragment.EXTRA_CODE);
      //tvCooperativeRegion.setText(data.getStringExtra(AddressSelectDialogFragment.EXTRA_NAME));

      SimpleTreeListParams params =
          (SimpleTreeListParams) data.getSerializableExtra(BaseFragment.EXTRA_PARAMS);
      SysDistrict item = ((SysDistrict) params.getItem());
      tvCooperativeRegion.setText(item.getDistrictName());
      mCooperativeRegionCode = item.getCode();
    }
  }
}
